package com.shiyi.design.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察者（事件源）
 * @author wangzhanshuai
 * @date 2021/2/1 11:20 下午
 * @since 1.0
 */
public class Baby {

    private List<ActionListener> listenerList = new ArrayList<>();

    private final Object lock = new Object();

    public void addListener(ActionListener listener) {
        if(listenerList.size() < 3) {
            synchronized (lock) {
                if(listenerList.size() < 3) {
                    listenerList.add(listener);
                }
            }
        }
    }

    public void wakeUp() {
        System.out.println("baby is wakeup, wu wu wu......");
        ActionEvent event = new ActionEvent();
        event.setReason("wakeUp");
        event.setSource(this);
        for (ActionListener actionListener : listenerList) {
            actionListener.handle(event);
        }
    }

    public void hunger() {
        System.out.println("baby is hunger, wu wu wu......");
        ActionEvent event = new ActionEvent();
        event.setReason("hunger");
        event.setSource(this);
        for (ActionListener actionListener : listenerList) {
            actionListener.handle(event);
        }
    }

    public void stopCry() {
        System.out.println("baby stop cry......");
    }

}
